using RimWorld;
using RimWorld.Planet;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;

namespace TW_Rainbow_Land
{
    // GameCondition_VolcanicAsh
    public class GameCondition_RageFury : GameCondition
    {
        int lastEffectTick = 0; // 上次生效的时间
        public override void Init()
        {
            base.Init();
        }

        public override void GameConditionTick()
        {
            if (Find.TickManager.TicksGame - lastEffectTick < 60000)
            {
                // 每天只触发一次
                return;
            }
            if (Find.TickManager.TicksGame % 9891 != 0)
            {
                // 每9891个Tick触发一次
                return;
            }
            base.GameConditionTick();


            lastEffectTick = Find.TickManager.TicksGame;
            
            try
            {
                // 获取本地图所有Pawn
                List<Pawn> livingPawns = new List<Pawn>();
                if (AffectedMaps != null)
                {
                    foreach (Map map in AffectedMaps)
                    {
                        livingPawns.AddRange(map.mapPawns.AllPawnsSpawned.Where(p => !p.Dead).Where(p => p.RaceProps.Humanlike || p.RaceProps.Animal));
                    }
                }

                if (livingPawns.Count == 0)
                {
                    return;
                }

                // 随机选择一个Pawn
                Pawn selectedPawn = livingPawns.RandomElement();
                // 触发愤怒状态
                if (selectedPawn.mindState != null && selectedPawn.mindState.mentalStateHandler != null)
                {
                    selectedPawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, "GameCondition_RageFury_Reason".Translate(), true, true);
                }
            }
            catch (System.Exception ex)
            {
                Log.Error($"[TW_Rainbow_Land] GameCondition_RageFury encountered an error: {ex.Message}\n{ex.StackTrace}");
                End();
            }
        }
    }
}